import {Injectable, Inject, InjectionToken} from '@angular/core';
import {Observable, throwError} from 'rxjs';
import {catchError, map } from 'rxjs/operators';
import {
  HttpHeaders,
  HttpClient,
  HttpErrorResponse
} from '@angular/common/http';

// 请求头
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'app-type': 'release8310',
    'APP-Version-Code': '728',
    'App-Version-Number': '824',
    'Product-Code': '4' // 请求头区分调用来源 4 店铺管家   5龙掌柜
  })
};

export const API_URL = new InjectionToken<string>('apiUrl');

@Injectable({
  providedIn: 'root'
})

export class ApiService {
  constructor(
    private http: HttpClient,
    @Inject(API_URL) public urlPrefix) {
  }

  /**
   *  GET请求处理（一般用于获取数据）
   * @param url 后台接口api 例如：/api/test/6
   */
  get(url: string): Observable<any> {
    return this.http.get(this.urlPrefix + url, httpOptions).pipe(
      map(this.extractData),
      catchError(this.handleError)
    );
  }

  /**
   * POST请求处理（一般用于保存数据）
   * @param url 后台接口api
   * @param data 参数
   */
  post(url: string, data = {}): Observable<any> {
    return this.http.post(this.urlPrefix + url, data, httpOptions).pipe(
      catchError(this.handleError)
    );
  }


  /**
   *  提取数据
   * @param res 返回结果
   */
  extractData(res: Response) {
    return res || {};
  }

  /**
   *
   *http错误捕捉
   * @param {HttpErrorResponse} error
   * @returns
   * @memberof HttpService
   */
  handleError = (error: HttpErrorResponse) => {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.log(error.error.message);
      // 发生客户端或者网络错误提醒用户
    } else {
      console.log(this);
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError(
      'Something bad happened; please try again later.');
  }

}
